//
//  LineManagementViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/23.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "LineManagementViewController.h"
#import "ComLineModel.h"
#import "ReleaseRateViewController.h"

static NSString *cellPath = @"LineManagCell";
@interface LineManagementViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *leftBtn;
    UIButton *rightBtn;
    UIView *lineView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSMutableArray *allLineAry;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, assign)NSInteger closeType;
@property (nonatomic, strong)NSString *wlPhone;

@end

@implementation LineManagementViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(callPhonesNotifice:) name:@"callPhones" object:nil];
    if (_isEdit)
    {
        [self loadNewHeaderData];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callPhones" object:nil];
}


- (void)callPhonesNotifice:(NSNotification *)center
{
    NSString *timeStr = [center object];
    Student *stu = [Student studentWith:@"" name:@"专线网" Phone:_wlPhone Times:timeStr];
    BOOL isInsert = [StudentFMDNManager addStudent:stu];
    if (isInsert) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _allLineAry = [NSMutableArray arrayWithCapacity:0];
    if (!_isEdit)
    {
        _wlPhone = @"";
        self.navigationItem.title = @"线路管理";
        self.navigationController.navigationBar.translucent = NO;
        self.view.backgroundColor = BacksColor;
        UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 100*displaywidth, SCREEN_WIDTH-40*displaywidth, 50*displaywidth) Font:14.0 Text:@"您没有发布线路价格的权限，需要向总部申请，\n开通后才可发布。" Color:BlaTitColor];
        tostLab.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:tostLab];
        UIButton *callBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth, 200*displaywidth, SCREEN_WIDTH-120*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(callBtnAction) Title:@"我要发布整车价" Font:16.0];
        callBtn.backgroundColor = RGB(255, 153, 0);
        [callBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        callBtn.layer.cornerRadius = 5;
        callBtn.layer.masksToBounds = YES;
        [self.view addSubview:callBtn];
    }
    else
    {
        [self creatUI];
        [self requestFreight];
    }
    
}

- (void)callBtnAction
{
    if ([_wlPhone isEqualToString:@""])
    {
        [self requestServicePhone];
        return;
    }
    NSMutableString* str= [[NSMutableString alloc] initWithFormat:@"telprompt://%@",_wlPhone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

- (void)creatUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    CGFloat H = 0;
    if (_isTrucks)
    {
        H = 45*displaywidth;
        self.navigationItem.title = @"线路管理";
        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45*displaywidth)];
        topView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:topView];
        leftBtn = [ZCControl createButtonWithFrame:CGRectMake(50*displaywidth, 0, SCREEN_WIDTH/2-50*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(leftAction) Title:@"零担价" Font:15.0];
        leftBtn.backgroundColor = [UIColor clearColor];
        [leftBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [topView addSubview:leftBtn];
        rightBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2-50*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(rightAction) Title:@"整车价" Font:15.0];
        rightBtn.backgroundColor = [UIColor clearColor];
        [rightBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        [topView addSubview:rightBtn];
        lineView = [[UIView alloc] initWithFrame:CGRectMake(50*displaywidth, 43.5*displaywidth, SCREEN_WIDTH/2-50*displaywidth, 1.5*displaywidth)];
        lineView.backgroundColor = ThemeColor;
        [topView addSubview:lineView];
        _closeType = 0;

    }
    else
    {
        self.navigationItem.title = @"整车价";
        _closeType = 1;

    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-H-65*displaywidth-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displaywidth-SCREER_HeiX, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"发布运价" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [self.view addSubview:soureBtn];
    
}

- (void)loadNewHeaderData
{
    _page = 0;
    [self requestFreight];
    
}

- (void)loadMoreFootData
{
    _page ++;
    [self requestFreight];
    
}

- (void)leftAction
{
    if (_closeType != 0)
    {
        _closeType = 0;
        [leftBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [rightBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        lineView.frame = CGRectMake(50*displaywidth, 43.5*displaywidth, SCREEN_WIDTH/2-50*displaywidth, 1.5*displaywidth);
        [self loadNewHeaderData];
    }
    
}

- (void)rightAction
{
    if (_closeType != 1)
    {
        _closeType = 1;
        [rightBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [leftBtn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        lineView.frame = CGRectMake(SCREEN_WIDTH/2, 43.5*displaywidth, SCREEN_WIDTH/2-50*displaywidth, 1.5*displaywidth);
        [self loadNewHeaderData];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allLineAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = BacksColor;
    if (_allLineAry.count > 0)
    {
        ComLineModel *model = _allLineAry[indexPath.row];
        UIView *whiteAview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, 10*displaywidth, SCREEN_WIDTH-20*displaywidth, 130*displaywidth)];
        whiteAview.backgroundColor = [UIColor whiteColor];
        whiteAview.layer.cornerRadius = 10;
        whiteAview.layer.masksToBounds = YES;
        [cell.contentView addSubview:whiteAview];
        UILabel *startALab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 15*displaywidth, 100*displaywidth, 20*displaywidth) Font:15.0 Text:model.shipmentName Color:BlaTitColor];
        startALab.textAlignment = NSTextAlignmentLeft;
        [whiteAview addSubview:startALab];
        CGRect bound1 = [startALab.text boundingRectWithSize:CGSizeMake(500*displaywidth, 20*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
        CGFloat W = bound1.size.width+10*displaywidth;
        startALab.frame = CGRectMake(10*displaywidth, 15*displaywidth, W, 20*displaywidth);
        W+=10*displaywidth;
        UIImageView *zhiXimgView = [ZCControl createImageViewWithFrame:CGRectMake(W, 20*displaywidth, 30*displaywidth, 10*displaywidth) ImageName:@"zxli_icon01"];
        zhiXimgView.contentMode = UIViewContentModeScaleAspectFit;
        [whiteAview addSubview:zhiXimgView];
        W+=40*displaywidth;
        UILabel *stopALab = [ZCControl createLabelWithFrame:CGRectMake(W, 15*displaywidth, 100*displaywidth, 20*displaywidth) Font:15.0 Text:model.destinationname Color:BlaTitColor];
        stopALab.textAlignment = NSTextAlignmentLeft;
        [whiteAview addSubview:stopALab];
        CGRect bound2 = [stopALab.text boundingRectWithSize:CGSizeMake(500*displaywidth, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
        stopALab.frame = CGRectMake(W, 15*displaywidth, bound2.size.width+10*displaywidth, 20*displaywidth);
        CGFloat H = 85*displaywidth;
        if (_closeType == 0)
        {
            UILabel *puLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 37.5*displaywidth, 15*displaywidth, 15*displaywidth) Font:10 Text:@"普" Color:[UIColor whiteColor]];
            puLab.textAlignment = NSTextAlignmentCenter;
            puLab.backgroundColor = ThemeColor;
            puLab.layer.cornerRadius = 2;
            puLab.layer.masksToBounds = YES;
            [whiteAview addSubview:puLab];
            
            UILabel *lenthLab = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 35*displaywidth, SCREEN_WIDTH-80*displaywidth, 20*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.pHeavyPrice,model.pLowPrice,model.pTimeBar] Color:BlaTitColor];
            NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.pHeavyPrice,model.pLowPrice,model.pTimeBar]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range1 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.pHeavyPrice]];
            NSRange range2 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.pLowPrice]];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range1];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range2];
            lenthLab.attributedText = hintString;
            [whiteAview addSubview:lenthLab];
            
            UILabel *kuaiLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 57.5*displaywidth, 15*displaywidth, 15*displaywidth) Font:10 Text:@"快" Color:[UIColor whiteColor]];
            kuaiLab.textAlignment = NSTextAlignmentCenter;
            kuaiLab.backgroundColor = RGB(255, 153, 0);
            kuaiLab.layer.cornerRadius = 2;
            kuaiLab.layer.masksToBounds = YES;
            [whiteAview addSubview:kuaiLab];
            UILabel *lenthBLab = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 55*displaywidth, SCREEN_WIDTH-80*displaywidth, 20*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.kHeavyPrice,model.kLowPrice,model.kTimeBar] Color:BlaTitColor];
            NSMutableAttributedString *hintBString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元/吨   ￥%@元/方  %@天",model.kHeavyPrice,model.kLowPrice,model.kTimeBar]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range3 = [[hintBString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.kHeavyPrice]];
            NSRange range4 = [[hintBString string]rangeOfString:[NSString stringWithFormat:@"￥%@",model.kLowPrice]];
            [hintBString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range3];
            [hintBString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range4];
            lenthBLab.attributedText = hintBString;
            [whiteAview addSubview:lenthBLab];
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, 84*displaywidth, SCREEN_WIDTH-40*displaywidth, 1)];
            lineBview.backgroundColor = RGB(243, 245, 249);
            [whiteAview addSubview:lineBview];
        }
        else
        {
            H = 70*displaywidth;
            whiteAview.frame = CGRectMake(10*displaywidth, 10*displaywidth, SCREEN_WIDTH-20*displaywidth, 115*displaywidth);
            UIImageView *carImgView = [ZCControl createImageViewWithFrame:CGRectMake(10*displaywidth, 40*displaywidth, 15*displaywidth, 15*displaywidth) ImageName:@"lb_icon33"];
            carImgView.contentMode = UIViewContentModeScaleAspectFit;
            [whiteAview addSubview:carImgView];
            UILabel *lenthLab = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 35*displaywidth, SCREEN_WIDTH-80*displaywidth, 25*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"%@米/%@   ￥%@元左右",model.length,model.truckType,model.price] Color:BlaTitColor];
            NSMutableAttributedString *hintString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@米/%@   ￥%@元左右",model.length,model.truckType,model.price]];
            //获取要调整颜色的文字位置,调整颜色
            NSRange range1 = [[hintString string]rangeOfString:[NSString stringWithFormat:@"￥%@元左右",model.price]];
            [hintString addAttribute:NSForegroundColorAttributeName value:RGB(230, 67, 64) range:range1];
            lenthLab.attributedText = hintString;
            [whiteAview addSubview:lenthLab];
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, 69*displaywidth, SCREEN_WIDTH-40*displaywidth, 1)];
            lineBview.backgroundColor = RGB(243, 245, 249);
            [whiteAview addSubview:lineBview];
        }
        
        NSString *timestr = [self timeIntervalFromLastTime:model.createDtm lastTimeFormat:@"yyyy-MM-dd HH:mm:ss"];
        UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, H + 5*displaywidth, 150*displaywidth, 35*displaywidth) Font:13.0 Text:timestr Color:RGB(178, 178, 178)];
        [whiteAview addSubview:timeLab];
        
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-120*displaywidth, H+5*displaywidth, 90*displaywidth, 35*displaywidth) ImageName:nil Target:self Action:@selector(delecteAction:) Title:@"删除" Font:13.0];
        btn.backgroundColor = [UIColor clearColor];
        [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
        btn.contentVerticalAlignment = 0;
        btn.contentHorizontalAlignment = 2;
        btn.tag = 1000+indexPath.row;
        [whiteAview addSubview:btn];
        
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_closeType == 0)
    {
        return 140*displaywidth;
    }
    return 125*displaywidth;
}

- (void)delecteAction:(UIButton *)btn
{
    NSInteger index = btn.tag-1000;
    ComLineModel *model = _allLineAry[index];
    WEAKSELF;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除该条线路信息" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf requestDeleteCargo:s_str(model.ID)];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:okAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)requestDeleteCargo:(NSString *)idstr
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":idstr};
    [HYBaseHandler requestWithTheFormUrl:SERVER_deletelineMine Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"删除成功" addToView:weakSelf.view];
            [weakSelf requestFreight];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}



- (void)requestFreight
{
    WEAKSELF;
    NSDictionary *dic = @{ @"type":s_Integer(_closeType+1),
                           @"page":s_Integer(_page),
                           @"size":@"10"};
    [HYBaseHandler requestWithTheFormUrl:SERVER_lineMine Parmers:dic Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *lineAry = [ComLineModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_page == 0)
                {
                    [weakSelf.allLineAry removeAllObjects];
                }
                [weakSelf.allLineAry addObjectsFromArray:lineAry];
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)requestServicePhone
{
    WEAKSELF;
    [HYBaseHandler requestServicePhoneParmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            weakSelf.wlPhone = [NSString stringWithFormat:@"%@",obj[@"data"]];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}


- (void)soureBtnAction
{
    ReleaseRateViewController *vc = [[ReleaseRateViewController alloc] init];
    vc.isTrucks = _isTrucks;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormat:(NSString *)format1
{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    //    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    //    dateFormatter2.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    //    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:[NSDate date]];
    
}
- (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10)
    {
        return  @"刚刚";
    }
    else if (minutes < 60)
    {
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }
    else if (hours < 24)
    {
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30)
    {
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12)
    {
        return [NSString stringWithFormat: @"%ld月前",(long)month];
    }
    else if (yers >= 1){
        return [NSString stringWithFormat: @"%ld年前",(long)yers];
    }
    return @"";
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
